package com.playtruly.wanzhende2025

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

// 🗺️ 高德地图隐私合规导入
import com.amap.api.location.AMapLocationClient

class MainActivity : FlutterActivity() {
    
    // 高德地图定位服务
    private var amapLocationService: AmapLocationService? = null
    
    // 🔥 微信分享Method Channel
    private val WECHAT_CHANNEL = "wechat_share"
    
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        
        android.util.Log.d("MainActivity", "🚀 =============== MainActivity Flutter引擎配置开始 ===============")
        
        // 🗺️ 第三重保险：在MainActivity中也设置隐私合规
        ensureAmapPrivacyCompliance()
        
        try {
            // 🔥 暂时禁用可能导致闪退的日志过滤插件
            // LogFilter.registerWith(flutterEngine)
            
            // 🗺️ 注册高德地图定位服务Platform Channel（学习MyApplication2实现）
            setupAmapLocationService(flutterEngine)
            
            // 🗺️ 注册高德地图Platform View
            setupAmapMapView(flutterEngine)
            
            // 🔥 注册微信分享服务
            setupWeChatShareService(flutterEngine)
            
            android.util.Log.d("MainActivity", "✅ Flutter引擎配置成功")
        } catch (e: Exception) {
            android.util.Log.e("MainActivity", "💥 Flutter引擎配置异常: ${e.message}", e)
        }
        
        android.util.Log.d("MainActivity", "🏁 =============== MainActivity Flutter引擎配置完成 ===============")
    }
    
    /**
     * 🗺️ 确保高德地图隐私合规设置（第三重保险）
     * 
     * 在MainActivity中再次设置，确保隐私合规在任何时候都已生效
     */
    private fun ensureAmapPrivacyCompliance() {
        try {
            android.util.Log.d("MainActivity", "🔍 =============== MainActivity隐私合规设置 ===============")
            
            // 🔑 在MainActivity中设置隐私合规
            AMapLocationClient.updatePrivacyShow(this.applicationContext, true, true)
            AMapLocationClient.updatePrivacyAgree(this.applicationContext, true)
            
            android.util.Log.d("MainActivity", "✅ MainActivity隐私合规设置完成")
            android.util.Log.d("MainActivity", "🔍 =============== MainActivity隐私合规设置结束 ===============")
            
        } catch (e: Exception) {
            android.util.Log.e("MainActivity", "💥 MainActivity隐私合规设置失败: ${e.message}", e)
        }
    }
    
    /**
     * 设置高德地图定位服务
     */
    private fun setupAmapLocationService(flutterEngine: FlutterEngine) {
        try {
            android.util.Log.d("MainActivity", "🔧 开始注册高德地图定位服务...")
            
            // 创建高德定位服务实例
            amapLocationService = AmapLocationService(this)
            android.util.Log.d("MainActivity", "📦 AmapLocationService实例创建成功")
            
            // 注册Platform Channel
            MethodChannel(
                flutterEngine.dartExecutor.binaryMessenger,
                AmapLocationService.CHANNEL_NAME
            ).setMethodCallHandler(amapLocationService)
            
            android.util.Log.d("MainActivity", "✅ 高德地图定位服务注册成功")
            android.util.Log.d("MainActivity", "📡 Channel名称: ${AmapLocationService.CHANNEL_NAME}")
            
        } catch (e: Exception) {
            android.util.Log.e("MainActivity", "💥 高德地图定位服务注册失败: ${e.message}", e)
            android.util.Log.e("MainActivity", "🔍 异常堆栈: ${e.stackTraceToString()}")
        }
    }
    
    /**
     * 设置高德地图Platform View
     */
    private fun setupAmapMapView(flutterEngine: FlutterEngine) {
        try {
            android.util.Log.d("MainActivity", "🔧 开始注册高德地图Platform View...")
            
            // 注册Platform View Factory
            flutterEngine.platformViewsController.registry.registerViewFactory(
                MapViewFactory.VIEW_TYPE,
                MapViewFactory(flutterEngine.dartExecutor.binaryMessenger)
            )
            
            android.util.Log.d("MainActivity", "✅ 高德地图Platform View注册成功")
            android.util.Log.d("MainActivity", "📡 View类型: ${MapViewFactory.VIEW_TYPE}")
            
        } catch (e: Exception) {
            android.util.Log.e("MainActivity", "💥 高德地图Platform View注册失败: ${e.message}", e)
            android.util.Log.e("MainActivity", "🔍 异常堆栈: ${e.stackTraceToString()}")
        }
    }
    
    /**
     * 🔥 设置微信分享服务
     */
    private fun setupWeChatShareService(flutterEngine: FlutterEngine) {
        try {
            android.util.Log.d("MainActivity", "🔧 开始注册微信分享服务...")
            
            // 注册微信分享Method Channel
            MethodChannel(flutterEngine.dartExecutor.binaryMessenger, WECHAT_CHANNEL)
                .setMethodCallHandler { call, result ->
                    when (call.method) {
                        "initWeChatAPI" -> {
                            val success = WeChatShareHelper.initWeChatAPI(this)
                            result.success(success)
                        }
                        "isWeChatInstalled" -> {
                            val installed = WeChatShareHelper.isWeChatInstalled()
                            result.success(installed)
                        }
                        "shareToWeChat" -> {
                            val title = call.argument<String>("title") ?: ""
                            val description = call.argument<String>("description") ?: ""
                            val webUrl = call.argument<String>("webUrl") ?: ""
                            val thumbUrl = call.argument<String?>("thumbUrl")
                            val isTimeline = call.argument<Boolean>("isTimeline") ?: false
                            
                            val success = WeChatShareHelper.shareToWeChat(
                                title, description, webUrl, thumbUrl, isTimeline
                            )
                            result.success(success)
                        }
                        "getWXAppSupportAPI" -> {
                            val apiVersion = WeChatShareHelper.getWXAppSupportAPI()
                            result.success(apiVersion)
                        }
                        else -> {
                            result.notImplemented()
                        }
                    }
                }
            
            android.util.Log.d("MainActivity", "✅ 微信分享服务注册成功")
            android.util.Log.d("MainActivity", "📡 Channel名称: $WECHAT_CHANNEL")
            
        } catch (e: Exception) {
            android.util.Log.e("MainActivity", "💥 微信分享服务注册失败: ${e.message}", e)
        }
    }
    
    override fun onDestroy() {
        try {
            // 销毁高德定位服务
            amapLocationService?.destroy()
            amapLocationService = null
            
            android.util.Log.d("MainActivity", "🗑️ Activity销毁，高德定位服务已清理")
        } catch (e: Exception) {
            android.util.Log.e("MainActivity", "💥 销毁Activity异常: ${e.message}", e)
        }
        
        super.onDestroy()
    }
}
